package com.yami.shop.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.enums.ShopWalletChangeReason;
import com.yami.shop.bean.event.PaySuccessOrderEvent;
import com.yami.shop.bean.model.ShopWallet;
import com.yami.shop.bean.order.PaySuccessOrderOrder;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.dao.ProductMapper;
import com.yami.shop.dao.ShopWalletMapper;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.ShopWalletLogService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 支付成功回调
 *
 * @author LGH
 */
@Component("defaultPaySuccessListener")
@AllArgsConstructor
@Slf4j
public class PaySuccessOrderListener {

    private final ShopWalletMapper shopWalletMapper;

    private final ShopWalletLogService shopWalletLogService;

    private final MapperFacade mapperFacade;

    private final ProductMapper productMapper;

    private final OrderService orderService;

    /**
     * 更新店铺钱包信息
     */
    @EventListener(PaySuccessOrderEvent.class)
    @Order(PaySuccessOrderOrder.DEFAULT)
    public void defaultPaySuccessListener(PaySuccessOrderEvent event) {
        if(Objects.equals(event.getOrders().get(0).getShopId(),Constant.PLATFORM_SHOP_ID)){
            return;
        }
        List<com.yami.shop.bean.model.Order> orders = event.getOrders();

        for (com.yami.shop.bean.model.Order order : orders) {
            Long shopId = order.getShopId();
            ShopWallet shopWallet = shopWalletMapper.selectOne(new LambdaQueryWrapper<ShopWallet>().eq(ShopWallet::getShopId, shopId));
            ShopWallet newShopWallet = mapperFacade.map(shopWallet, ShopWallet.class);
            newShopWallet.setUpdateTime(new Date());

            // 商家未结算金额 = 商家原未结算金额 + 订单实付金额 + 订单平台补贴金额
            newShopWallet.setUnsettledAmount(Arith.add(shopWallet.getUnsettledAmount(), Arith.add(order.getActualTotal(),order.getPlatformAmount())));
            // 插入未结算收入记录
            shopWalletLogService.saveShopWalletLog(shopWallet, newShopWallet, ShopWalletChangeReason.PAY, order.getOrderNumber());
            // 使用乐观锁进行更新
            if (shopWalletMapper.updateById(newShopWallet) != 1) {
                // 更新店铺钱包信息失败
//                throw new YamiShopBindException("yami.cannot.update.wallet");
                log.error("更新店铺钱包失败，无法确认收货，稍后再试");
                // 不要让用户看到更新店铺钱包失败的信息
                // 网络繁忙，请稍后重试
                throw new YamiShopBindException("yami.network.busy");
            }
        }
        // 更新商品销量
        productMapper.updateSoldNum(event.getAllOrderItems());
    }
}
